﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Diagnostics;
using LOGISTCBUS.Entities;

namespace LOGISTCBUS.DAO
{
    public class UserDAO : BaseDAO
    {
        #region public methods
        public Boolean insert(User u)
        {
            var db = new Db();
            db.Connect();
            String sql = "insert into users (name, login, password, email, insert_date, id_city, description) ";
            sql += "values (@name, @login, @password, @email, @insert_date, @id_city, @description);";
            var parameters = new Dictionary<String, Object>();
            parameters["@name"] = u.Name;
            parameters["@login"] = u.Login;
            parameters["@password"] = u.Password;
            parameters["@email"] = u.Email;
            parameters["@insert_date"] = DateTime.Now;
            parameters["@id_city"] = u.City != null ? u.City.Id : new Nullable<Int32>();
            parameters["@description"] = u.Description;
            try
            {
                var sucess = db.Execute(sql, parameters);
                db.Commit();
                db.Disconnect();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                db.Rollback();
                db.Disconnect();
                return false;
                throw ex;
            }
        }

        public Boolean update(User u)
        {
            var db = new Db();
            db.Connect();
            String sql = "update users set name = @name, login = @login, password = @password, email = @email, ";
            sql += "insert_date = @insert_date, id_city = @id_city, description = @description where id= @id;";
            var parameters = new Dictionary<String, Object>();
            parameters["@name"] = u.Name;
            parameters["@login"] = u.Login;
            parameters["@password"] = u.Password;
            parameters["@email"] = u.Email;
            parameters["@insert_date"] = u.InsertDate;
            parameters["@id_city"] = u.City != null ? u.City.Id : new Nullable<Int32>();
            parameters["@description"] = u.Description;
            parameters["@id"] = u.Id;
            try
            {
                var sucess = db.Execute(sql, parameters);
                db.Commit();
                db.Disconnect();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                db.Rollback();
                db.Disconnect();
                return false;
                throw ex;
            }
        }

        public User selectById(Int32 id)
        {
            var db = new Db();
            db.Connect();
            var dt = db.Select("select * from users where id = " + id);
            db.Disconnect();
            if (dt == null || dt.Rows.Count <= 0)
                return null;
            DataRow r = dt.Rows[0];
            var obj = new User()
            {
                Id = Convert.ToInt32(r["id"]),
                Name = r["name"].ToString(),
                Login = r["login"].ToString(),
                Password = r["password"].ToString(),
                Email = r["email"] is DBNull ? string.Empty : r["email"].ToString(),
                City = r["id_city"] is DBNull ? new City() : new City() { Id = Convert.ToInt32(r["id_city"]) },
                InsertDate = Convert.ToDateTime(r["insert_date"]),
                Description = r["description"] is DBNull ? string.Empty : r["description"].ToString(),
                Removed = Convert.ToBoolean(r["removed"])
            };
            return obj;
        }

        public List<User> select()
        {
            var db = new Db();
            db.Connect();
            var lst = new List<User>();
            var dt = db.Select("select * from users where removed = 0 order by name");
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new User()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Name = r["name"].ToString(),
                    Login = r["login"].ToString(),
                    Password = r["password"].ToString(),
                    Email = r["email"] is DBNull ? string.Empty : r["email"].ToString(),
                    City = r["id_city"] is DBNull ? new City() : new City() { Id = Convert.ToInt32(r["id_city"]) },
                    InsertDate = Convert.ToDateTime(r["insert_date"]),
                    Description = r["description"] is DBNull ? string.Empty : r["description"].ToString(),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst;
        }

        public List<User> select(String name, Int32 page, Int32 pageSize)
        {
            var db = new Db();
            db.Connect();
            var lst = new List<User>();
            var sql = "select * from users where removed = 0";
            if (!String.IsNullOrEmpty(name))
                sql += " and name like '%" + name + "%'";
            sql += " order by name";
            var dt = db.Select(sql);
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new User()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Name = r["name"].ToString(),
                    Login = r["login"].ToString(),
                    Password = r["password"].ToString(),
                    Email = r["email"] is DBNull ? string.Empty : r["email"].ToString(),
                    City = r["id_city"] is DBNull ? new City() : new City() { Id = Convert.ToInt32(r["id_city"]) },
                    InsertDate = Convert.ToDateTime(r["insert_date"]),
                    Description = r["description"] is DBNull ? string.Empty : r["description"].ToString(),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }

        public Int32 getCount(String name)
        {
            var count = 0;
            var db = new Db();
            db.Connect();
            var lst = new List<User>();
            var sql = "select count(*) as qtd from users where removed = 0";
            if (!String.IsNullOrEmpty(name))
                sql += " and name like '%" + name + "%'";
            var dt = db.Select(sql);
            db.Disconnect();
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                count = Convert.ToInt32(r["qtd"]);
            }
            return count;
        }

        public List<User> select(String filter)
        {
            var db = new Db();
            db.Connect();
            var lst = new List<User>();
            var dt = db.Select("select * from users where removed = 0 and " + getConditions(filter, "name") + " order by name");
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new User()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Name = r["name"].ToString(),
                    Login = r["login"].ToString(),
                    Password = r["password"].ToString(),
                    Email = r["email"] is DBNull ? string.Empty : r["email"].ToString(),
                    City = r["id_city"] is DBNull ? new City() : new City() { Id = Convert.ToInt32(r["id_city"]) },
                    InsertDate = Convert.ToDateTime(r["insert_date"]),
                    Description = r["description"] is DBNull ? string.Empty : r["description"].ToString(),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst;
        }

        public Boolean delete(User u)
        {
            var db = new Db();
            db.Connect();
            String sql = getSQLDeleteUpdate("users", "name");
            var parameters = new Dictionary<String, Object>();
            parameters["@id"] = u.Id;
            var sucess = db.Execute(sql, parameters);
            db.Commit();
            db.Disconnect();
            return sucess;
        }

        public Boolean delete(List<User> lst)
        {
            var db = new Db();
            db.Connect();
            var sucess = true;
            foreach (var u in lst)
            {
                String sql = getSQLDeleteUpdate("users", "name");
                var parameters = new Dictionary<String, Object>();
                parameters["@id"] = u.Id;
                sucess = db.Execute(sql, parameters);
            }
            db.Commit();
            db.Disconnect();
            return sucess;
        }

        public User doLogin(string login, string password)
        {
            var u = new User();
            var db = new Db();
            db.Connect();
            var sql = "select * from users where login = '" + login + "' and password = '" + password + "' order by name";
            var dt = db.Select(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                u = new User()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Name = r["name"].ToString(),
                    Login = r["login"].ToString(),
                    Password = r["password"].ToString(),
                    Email = r["email"] is DBNull ? string.Empty : r["email"].ToString(),
                    City = r["id_city"] is DBNull ? new City() : new City() { Id = Convert.ToInt32(r["id_city"]) },
                    InsertDate = Convert.ToDateTime(r["insert_date"]),
                    Description = r["description"] is DBNull ? string.Empty : r["description"].ToString(),
                    Removed = Convert.ToBoolean(r["removed"])
                };
            }
            db.Disconnect();
            return u;
        }
        #endregion
    }
}
